package net.begincode.searchWeb.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.begincode.searchCommon.bean.Param;
import net.begincode.searchCommon.bean.Response;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author hlj~宇晗
 * @create 2017-03-27 12:12
 **/
public class RequestAspect {
	Logger logger= LoggerFactory.getLogger(RequestAspect.class);
	@Pointcut("execution(* net.begincode.searchWeb.controller.*.*(..))")
	public void pointCut_(){
	}
	@Around("pointCut_()")
	public Object around(ProceedingJoinPoint proceedingJoinPoint){
		Object[] objects=proceedingJoinPoint.getArgs();
		for(int i=0;i<objects.length;i++){
			if(objects[i] instanceof  Param){
				Param param=(Param)objects[i];
				param.check();
			}
		}
		MethodSignature joinPointObject=(MethodSignature)proceedingJoinPoint.getSignature();
		//获取方法名
		Method method=joinPointObject.getMethod();
		//判断方法是否使用了response注解
		boolean flag=method.isAnnotationPresent(ResponseBody.class);
		Object returnObject=null;
		try {
			returnObject=proceedingJoinPoint.proceed();
		} catch (Throwable throwable) {
			throwable.printStackTrace();
		}
		//判定方法的返回值类型,注解+返回值为空
		if(flag && method.getReturnType().equals(Void.TYPE)){
			voidResponse();
		}
		//使用了注解，同时返回值不为空
		if(flag && !method.getReturnType().equals(Void.TYPE)){
			//生成了response响应对象,---->json对象
			return Response.success(returnObject);
		}else{
			return returnObject;
		}
	}
	private  void voidResponse(){
		//获取response对象
		HttpServletResponse response=
				((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		//json处理对象
		ObjectMapper objectMapper=new ObjectMapper();
		try {
			objectMapper.writeValue(response.getOutputStream(),Response.success());
		} catch (IOException e) {
			logger.error("Response error",e);
		}
	}
}
